package com.design.chain;


import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *责任链Bean监听器
 *
 * @author Zee
 * @date 2021年8月27日
 */
@Component
public class ChainLinkedListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(ChainLinked.class);
        ChainLinkedHandlerContext handlerMapping = event.getApplicationContext().getBean(ChainLinkedHandlerContext.class);
        Map<Integer, ChainLinkedHandler> handlers = new ConcurrentHashMap<>(16);
        beans.forEach((name, bean) -> {
            ChainLinked chanLinked = bean.getClass().getAnnotation(ChainLinked.class);
            handlers.put(chanLinked.value().code, (ChainLinkedHandler) bean);
        });
        handlerMapping.linkedHandler(handlers);
    }


}
